<template>
  <div class="recipient-selector">
    <!-- signUpType === '1' (用户选择模式 - 使用 el-select) -->
    <div v-if="signUpType === '1'" class="recipient-options-type1">
      <el-select
        v-model="internalSelectedUserIds"
        clearable
        filterable
        :loading="loadingUsers"
        multiple
        placeholder="请选择用户"
        remote
        :remote-method="fetchActivityUsers"
        reserve-keyword
        style="width: 100%"
        @change="handleUserSelectionChange"
      >
        <el-option v-for="item in userListForSelect" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
    </div>

    <!-- signUpType === '2' (部门选择模式 - 保留 PersonSelectorQvil 使用) -->
    <div v-else-if="signUpType === '2'" class="department-selector">
      <div class="selected-display clickable" @click="personSelectorVisible = true">
        <template v-if="selectedUserObjects.length > 0">
          <div class="selected-text">已选{{ selectedUserObjects.length }}人</div>
        </template>
        <div v-else class="placeholder-text">
          <i class="el-icon-plus"></i>
          点击选择人员
        </div>
      </div>
    </div>

    <!-- signUpType未设置或无效时的提示 -->
    <div v-else class="no-signup-type">
      <el-alert :closable="false" title="请先设置活动报名类型" type="warning" />
    </div>

    <!-- PersonSelectorQvil (仅用于 signUpType === '2') -->
    <person-selector-qvil
      v-if="signUpType === '2'"
      v-model="personSelectorVisible"
      :allow-empty="false"
      :default-selected="defaultSelectedForSelector"
      :multiple="true"
      @cancel="() => (personSelectorVisible = false)"
      @confirm="handlePersonSelectorConfirm"
    />
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import PersonSelectorQvil from '/@/components/PersonSelectorQvil/index.vue'
import type { User as PersonSelectorUser } from '/@/components/PersonSelectorQvil/types'
import { getSignUpType } from '/@/utils/activityHelper'
import request from '/@/utils/request' // 假设的请求工具路径
import { API } from '/@/views/notice/config' // 引入 API 配置

// 定义 el-select 使用的用户数据结构
interface SelectUser {
  id: string // 这个 id 将存储 userId
  name: string
}

// 组件属性
const props = defineProps({
  modelValue: {
    type: [Array, String, Object], // 允许 string 是为了兼容 'all'，但 signUpType=1 时 'all' 将被忽略
    default: null,
  },
  activityId: {
    // 新增 activityId prop
    type: String,
    required: false, // 根据你的需求，如果 activityId 总是可用，可以设为 true
    default: null,
  },
})

// 组件事件
const emit = defineEmits(['update:modelValue'])

// signUpType 的响应式引用
const signUpType = ref(getSignUpType())

// --- State for signUpType === '1' (el-select mode) ---
const loadingUsers = ref(false)
const userListForSelect = ref<SelectUser[]>([]) // 用于 el-select 的选项列表
const internalSelectedUserIds = ref<string[]>([]) // el-select 的 v-model

// --- State for signUpType === '2' (PersonSelectorQvil mode) ---
const selectedUserObjects = ref<PersonSelectorUser[]>([]) // 用于 PersonSelectorQvil 的数据
const personSelectorVisible = ref(false)

// Computed property for PersonSelectorQvil (signUpType === '2')
const defaultSelectedForSelector = computed(() => {
  // isAllModelValue 不再在此组件层面直接使用，因为 signUpType '1' 和 '2' 的 'all' 含义不同
  // 对于 signUpType '2'， PersonSelectorQvil 内部没有 'all' 的概念
  return selectedUserObjects.value
})

// 获取用户列表 (用于 el-select, signUpType === '1')
const fetchActivityUsers = async (query?: string) => {
  if (signUpType.value !== '1') {
    console.log('不加载用户数据: signUpType不是1')
    userListForSelect.value = []
    return
  }

  if (!props.activityId) {
    console.error('无法加载用户列表: 缺少activityId参数')
    userListForSelect.value = []
    return
  }

  console.log('开始获取用户列表, activityId:', props.activityId, '搜索关键词:', query)
  loadingUsers.value = true

  try {
    const params: { activityId: string; name?: string; mobile?: string } = {
      activityId: props.activityId,
    }
    if (query) {
      params.name = query // 假设API支持按name搜索，如果不支持，则忽略query或调整
    }

    // 输出请求参数以便调试
    console.log('用户列表请求参数:', params, 'API路径:', API.getPlayerAll)

    // 根据实际 API /api/player/all 的能力调整这里的参数
    const response: any = await request({
      url: API.getPlayerAll,
      method: 'get',
      params,
    })

    // 输出API响应详情以便调试
    console.log('用户列表API响应:', response)

    // 调整响应处理逻辑，适应可能的不同响应格式
    let userList: any[] = []

    // 场景1: 直接返回结果对象 { code, result: { rows } }
    if (response && response.code === 0 && response.result && Array.isArray(response.result.rows)) {
      userList = response.result.rows
      console.log(`场景1: 获取到${userList.length}个用户`)
    }
    // 场景2: 包装在data中 { data: { code, result: { rows } } }
    else if (response && response.data && response.data.code === 0 && response.data.result && Array.isArray(response.data.result.rows)) {
      userList = response.data.result.rows
      console.log(`场景2: 获取到${userList.length}个用户（来自response.data）`)
    }
    // 场景3: 直接返回数组 [{ id, name }]
    else if (Array.isArray(response)) {
      userList = response
      console.log(`场景3: 直接获取到${userList.length}个用户数组`)
    }
    // 场景4: 包装在data中，直接是数组 { data: [{ id, name }] }
    else if (response && Array.isArray(response.data)) {
      userList = response.data
      console.log(`场景4: 获取到${userList.length}个用户数组（来自response.data）`)
    }
    // 场景5: 包装在result中 { result: [{ id, name }] }
    else if (response && Array.isArray(response.result)) {
      userList = response.result
      console.log(`场景5: 获取到${userList.length}个用户数组（来自response.result）`)
    }
    // 不需要重复检查，移除场景6
    else {
      console.error('未识别的API响应格式:', response)
      userList = []
    }

    // 通用的映射逻辑，处理可能的字段名差异
    if (userList.length > 0) {
      userListForSelect.value = userList.map((user: any) => {
        // 优先使用 userId，如果不存在，则按原顺序查找 id, ID, user_id
        const idValue = String(user.userId || user.id || user.ID || user.user_id || '')
        const nameValue = user.name || user.userName || user.username || user.NAME || user.nickname || `用户${idValue}`
        return {
          id: idValue,
          name: nameValue,
        }
      })
      console.log('处理后的用户列表 (优先userId):', userListForSelect.value)
    } else {
      userListForSelect.value = []
      console.warn('未获取到用户数据或数据为空数组')
    }
  } catch (error) {
    userListForSelect.value = []
    console.error('获取用户列表异常:', error)
  } finally {
    loadingUsers.value = false
  }
}

// 当 el-select (signUpType === '1') 的选择变化时
const handleUserSelectionChange = (selectedIds: string[]) => {
  if (signUpType.value === '1') {
    emit('update:modelValue', selectedIds.length > 0 ? selectedIds : null)
  }
}

// PersonSelectorQvil @confirm (signUpType === '2')
const handlePersonSelectorConfirm = (payload: string[] | PersonSelectorUser[]) => {
  if (signUpType.value !== '2') return

  let userIdsToEmit: string[] = []
  let userObjectsToStore: PersonSelectorUser[] = []

  if (payload && payload.length > 0) {
    if (typeof payload[0] === 'string') {
      userIdsToEmit = payload as string[]
      userObjectsToStore = userIdsToEmit.map((id) => ({ id: String(id) }) as PersonSelectorUser)
    } else if (typeof payload[0] === 'object' && payload[0] !== null && 'id' in payload[0]) {
      userObjectsToStore = payload as PersonSelectorUser[]
      userIdsToEmit = userObjectsToStore.map((user) => String(user.id))
    } else {
      emit('update:modelValue', null)
      selectedUserObjects.value = []
      personSelectorVisible.value = false
      return
    }
    emit('update:modelValue', userIdsToEmit)
    selectedUserObjects.value = userObjectsToStore
  } else {
    emit('update:modelValue', null)
    selectedUserObjects.value = []
  }
  personSelectorVisible.value = false
}

// 监听 modelValue 从父组件的变化
watch(
  () => props.modelValue,
  (val) => {
    if (signUpType.value === '1') {
      if (val === 'all') {
        console.warn("RecipientSelector: 'all' is not a supported selection for signUpType '1' with el-select. Clearing selection.")
        internalSelectedUserIds.value = []
        emit('update:modelValue', null) // 通知父组件 'all' 已被清除
      } else if (Array.isArray(val)) {
        if (val.length > 0 && typeof val[0] === 'object' && val[0] !== null && ('userId' in val[0] || 'id' in val[0])) {
          // 假设父组件传来的是 PersonSelectorUser[] 或 SelectUser[] 或包含 userId/id 的对象数组
          // 优先使用 userId
          internalSelectedUserIds.value = (val as Array<{ id?: string; userId?: string }>).map((user) => String(user.userId || user.id))
        } else if (val.length > 0 && typeof val[0] === 'string') {
          // 假设父组件传来的是 string[] (user IDs)
          internalSelectedUserIds.value = val as string[]
        } else {
          internalSelectedUserIds.value = []
        }
      } else if (val === null || val === undefined) {
        internalSelectedUserIds.value = []
      } else {
        // 其他意外情况
        console.warn('RecipientSelector: Unexpected modelValue for signUpType "1":', val)
        internalSelectedUserIds.value = []
      }
    } else if (signUpType.value === '2') {
      if (val === 'all') {
        console.log("RecipientSelector (type 2): modelValue is 'all'. No direct action on selectedUserObjects.")
        selectedUserObjects.value = []
      } else if (Array.isArray(val)) {
        if (val.length === 0) {
          selectedUserObjects.value = []
        } else if (typeof val[0] === 'object' && val[0] !== null && ('userId' in val[0] || 'id' in val[0])) {
          // 优先使用 userId 填充 PersonSelectorUser 的 id
          selectedUserObjects.value = (val as Array<{ id?: string; userId?: string; name?: string }>).map((u) => ({
            id: String(u.userId || u.id || ''),
            name: u.name || '',
          })) as PersonSelectorUser[]
        } else if (typeof val[0] === 'string') {
          selectedUserObjects.value = val.map((id) => ({ id: String(id) }) as PersonSelectorUser)
        } else {
          selectedUserObjects.value = []
        }
      } else if (val === null || val === undefined) {
        selectedUserObjects.value = []
      }
    }
  },
  { immediate: true, deep: true }
)

// 监听 signUpType 和 activityId 的变化
watch(
  [signUpType, () => props.activityId],
  ([newSignUpType, newActivityId], [oldSignUpType, oldActivityId]) => {
    console.log('监听到变化 - signUpType:', newSignUpType, '原值:', oldSignUpType, 'activityId:', newActivityId, '原值:', oldActivityId)

    // 当 signUpType 切换时，或 activityId 变化 (且是 type 1) 时，重置选择和用户列表
    if (newSignUpType !== oldSignUpType) {
      console.log(`signUpType changed to: ${newSignUpType}. Clearing modelValue and lists.`)
      emit('update:modelValue', null)
      internalSelectedUserIds.value = []
      selectedUserObjects.value = []
      userListForSelect.value = [] // 清空 el-select 的选项
    } else if (newSignUpType === '1' && newActivityId !== oldActivityId) {
      console.log(`activityId changed for signUpType '1' to: ${newActivityId}. Clearing modelValue and lists.`)
      emit('update:modelValue', null) // activityId 变了，之前的选择可能无效
      internalSelectedUserIds.value = []
      userListForSelect.value = []
    }

    // 如果切换到 type '1' 且 activityId 有效，则获取用户
    if (newSignUpType === '1' && newActivityId) {
      console.log('触发初始用户列表加载')
      fetchActivityUsers() // 初始加载一次，或在 activityId 变化时加载
    } else if (newSignUpType === '1' && !newActivityId) {
      console.log('activityId无效，不加载用户列表')
      userListForSelect.value = [] // 如果没有 activityId，清空列表
    }
  },
  { immediate: true } // 改为immediate: true，确保初始值处理，修复可能的数据加载问题
)

// 监听 signUpType 从 localStorage 的变化 (保持原有逻辑)
watch(
  () => localStorage.getItem('signUpType'),
  (newValue) => {
    if (newValue !== null && newValue !== signUpType.value) {
      console.log(`signUpType changed from localStorage to: ${newValue}. Current component signUpType: ${signUpType.value}`)
      // 更新组件内部的 signUpType，这将触发上面的 watch([signUpType, ...])
      signUpType.value = newValue
    }
  }
)

onMounted(() => {
  console.log('RecipientSelector组件已挂载', 'signUpType:', getSignUpType(), 'activityId:', props.activityId)
  signUpType.value = getSignUpType() // 确保初始 signUpType 正确

  // 检查和输出父组件传入的初始值
  console.log('初始modelValue:', props.modelValue, 'typeof:', typeof props.modelValue)
  if (Array.isArray(props.modelValue)) {
    console.log('modelValue是数组，长度:', props.modelValue.length)
  }

  // 添加activityId检查
  if (!props.activityId) {
    console.warn('RecipientSelector挂载时未提供activityId，可能影响数据加载')
  }

  // 确保无论watch是否触发，都尝试加载一次数据
  if (signUpType.value === '1' && props.activityId) {
    console.log('组件挂载后主动加载用户列表')
    fetchActivityUsers()
  }
})

// 在onMounted之后暴露内部方法，允许父组件手动触发刷新
defineExpose({
  refreshUsers: fetchActivityUsers,
})
</script>

<style scoped>
.recipient-selector {
  width: 100%;
}

.recipient-options-type1 {
  /* display: flex; */ /* el-select 默认会撑满 */
  /* align-items: center; */
  margin-bottom: 12px;
}

.department-selector {
  width: 100%;
  margin-bottom: 12px;
}

.selected-display {
  display: flex;
  flex: 1;
  align-items: center;
  min-height: 32px;
  padding: 0 12px;
  font-size: 14px;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  transition: border-color 0.2s;
}

.selected-display.clickable {
  cursor: pointer;
}

.selected-display.clickable:hover {
  border-color: #409eff;
}

.selected-text {
  overflow: hidden;
  color: #606266;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.placeholder-text {
  color: #c0c4cc;
}

.placeholder-text .el-icon-plus {
  margin-right: 4px;
}

.no-signup-type {
  padding: 12px 0;
}
</style>
